"""
file_name：p2110.py
author：王鑫
date：2019-04-19
file_description：将 Powercast P2110 开发板串口中的数据进行持久化保存
"""
import os
import csv
import time


class P2110(object):
    """
    p2110 持久化类
    """
    def __init__(self):
        """
        初始化 p2110 所获取到的数据
        """
        self.p2110_dic = {}

    def write_to_file(self, file_name):
        """
        将数据保存到csv文件中
        :param file_name:保存文件名
        :return:
        """
        file_dir = os.path.join('data', time.strftime("%Y-%m-%d", time.localtime()))
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        csv_file = os.path.join(file_dir, file_name)
        with open(csv_file, 'a+') as f:
            w = csv.writer(f)
            if not os.path.getsize(csv_file):
                # 文件为空
                w.writerow(self.p2110_dic.keys())
            # 文件已经存在直接写入值
            w.writerow(self.p2110_dic.values())

    def save_to_db(self):
        """
        将数据保存到数据库中
        :return:
        """
        pass

    def get_info(self, data):
        """
        将接受到的data数据中的信息提取出来
        :param data: 接收到的数据
        :return:
        """
        # Light    96 lx\r\nTime 00:19:06 | dT 00:01 | RSSI  5.60mW | Humidity 61 % | Extrnl 1768 mV\r\n\r\nPacket #  489 | Node   0 | TX ID  002   | Temp   76.9 F |
        # \r\nPacket #  391 | Node   0 | TX ID  ---   | Temp   76.0 F | Light   144 lx\r\nTime 00:11:59 | dT 00:11 | RSSI  4.14mW | Humidity 61 % | Extrnl 1449 mV\r\n
        packet = int(data.split(b'|')[0].split(b' ')[-2])
        node = int(data.split(b'|')[1].split(b' ')[-2])

        tx_id_str = data.split(b'|')[2].split(b' ')[4]
        if tx_id_str != b'---':
            tx_id = int(tx_id_str)
        else:
            tx_id = 0

        temp_str = data.split(b'|')[3].split(b' ')[4]
        if temp_str != b'---':
            temp = float(temp_str)
        else:
            temp = 0

        light_list = data.split(b'|')[4].split(b' ')
        if len(light_list) == 9:
            light_str = light_list[5]
        else:
            light_str = light_list[4]
        if light_str != b'-----':
            light = int(light_str)
        else:
            light = 0

        p_time = str(data.split(b'|')[4].split(b' ')[-2])
        dt = str(data.split(b'|')[5].split(b' ')[-2])

        rssi_list = data.split(b'|')[6].split(b' ')
        if len(rssi_list) == 4:
            rssi = float(rssi_list[2][0:-2])
        else:
            rssi = 0.0

        humidity_str = data.split(b'|')[7].split(b' ')[-3]
        if humidity_str != b'---':
            humidity = int(humidity_str)
        else:
            humidity = 0

        extrnl_str = data.split(b'|')[8].split(b' ')[-2]
        if extrnl_str != b'---':
            extrnl = int(extrnl_str)
        else:
            extrnl = 0

        # 将数据封装为字典格式
        self.p2110_dic = {
            'Packet': packet,
            'Node': node,
            'TX ID': tx_id,
            'Temp(F)': temp,
            'Light': light,
            'Time': p_time,
            'dT': dt,
            'RSSI(mW)': rssi,
            'Humidity(%)': humidity,
            'Extrnl(mV)': extrnl
        }
